<template>
  <div>
    <div v-if="state.editCourierInformation">
      <a-form :form="form">
        <a-row :gutter="[32,24]">
          <a-col
            v-for="item in form.getFieldValue('tracking_numbering')"
            :key="item"
            :span="8"
            :style="'block'"
          >
            <a-form-item
              label="快递公司"
            >
              <courier-company-selection
                v-decorator="[`courier_information[${item}].courier_company_id`, { initialValue: [], rules: [{ required: true, message: '请选择快递公司' }] }]"
              />
            </a-form-item>
            <a-form-item
              label="快递单号"
            >
              <a-input
                v-decorator="[`courier_information[${item}].tracking_numbering`, { initialValue: '', rules: [{ required: true, message: '请填写快递单号' }] }]"
              />
            </a-form-item>

            <a-button
              v-show="form.getFieldValue('tracking_numbering') && form.getFieldValue('tracking_numbering').length > 1"
              :disabled="form.getFieldValue('tracking_numbering') && form.getFieldValue('tracking_numbering').length === 1"
              @click="() => removeTrackingNumbering(item)"
            >
              移除
            </a-button>
          </a-col>
        </a-row>
      </a-form>

      <a-button
        type="dashed"
        style="width: 100%; margin-top: 20px;"
        @click="addTrackingNumbering"
        v-show="form.getFieldValue('tracking_numbering') && form.getFieldValue('tracking_numbering').length < 6"
      >
        <a-icon type="plus"/>
        增加快递单号
      </a-button>

      <a-row v-if="state.button">
        <a-col span="3">
          <a-button
            :loading="state.submitButtonLoading"
            type="primary"
            style="margin-top: 20px;"
            @click="handleSubmit"
          >
            提交发货信息
          </a-button>
        </a-col>
        <a-col span="3" offset="2">
          <a-button
            type="primary"
            style="margin-top: 20px;"
            @click="state.editCourierInformation = false"
          >
            取消
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div v-if="!state.editCourierInformation">
      <a-row :gutter="[8,8]">
        <a-col :span="8" v-for="(information, index) in orderInfo.courier_information" :key="index">
          <a-row>
            <detail-list-item term="快递公司">{{ information.courier_company.name }}</detail-list-item>
          </a-row>
          <a-row>
            <detail-list-item term="快递单号">{{ information.tracking_numbering }}</detail-list-item>
          </a-row>
        </a-col>
      </a-row>

      <a-button v-if="state.button" type="primary" @click="state.editCourierInformation = true">
        编辑
      </a-button>
    </div>
  </div>
</template>

<script>
  import { getOrderInfo, patchOrderExpressDelivery } from '@/api/order'
  import Vue from 'vue'
  import CourierCompanySelection from '@/components/CourierCompanySelection/CourierCompanySelection'
  import DetailList from '@/components/DescriptionList/DescriptionList'

  const DetailListItem = DetailList.Item

  let trackingNumberingSort = 1

  export default {
    name: 'OrderDelivery',
    components: { CourierCompanySelection, DetailListItem },
    props: {
      id: {
        type: Number,
        default: null
      },
      showButton: {
        type: Boolean,
        default: true
      },
      directEdit: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      id: {
        handler: function (id) {
          if (id) {
            getOrderInfo(id).then(res => {
              this.orderInfo = res
              // 初始化发货信息
              if (res.status === 2 && res.courier_information.length > 0) {
                let numbering = []
                const newInformation = []
                res.courier_information.forEach((information, index) => {
                  newInformation[trackingNumberingSort] = {
                    courier_company_id: [information.courier_company_id],
                    tracking_numbering: information.tracking_numbering
                  }
                  numbering = numbering.concat(trackingNumberingSort++)
                })
                this.form.setFieldsValue({ tracking_numbering: numbering }) // 这个先, 渲染出 form

                this.$nextTick(_ => {
                  this.form.setFieldsValue({ courier_information: newInformation }) // 然后下一个 tick 填充值
                })
              } else {
                // 这里再赋值一遍, 粗暴解决 "增加快递单号" 按钮不显示的问题
                this.form.setFieldsValue({ tracking_numbering: [] })
              }
            })
          }
        },
        immediate: true
      }
    },
    created () {
      this.form = this.$form.createForm(this)
      this.form.getFieldDecorator('tracking_numbering', { initialValue: [], preserve: true })
    },
    data () {
      return {
        state: {
          submitButtonLoading: false,
          editCourierInformation: this.directEdit,
          button: this.showButton
        },

        form: null,
        order_id: this.id,
        orderInfo: {}
      }
    },
    methods: {
      /**
       * 编辑发货信息
       */
      handleSubmit () {
        return new Promise((resolve, reject) => {
          const { form, state } = this

          state.submitButtonLoading = true
          form.validateFields()
            .then((values, err) => {
              if (err) {
                state.submitButtonLoading = false
                reject(err)
              }

              patchOrderExpressDelivery({
                order_id: this.orderInfo.id,
                courier_information: values.courier_information.filter(item => item).map(item => {
                  return {
                    courier_company_id: item.courier_company_id[0],
                    tracking_numbering: item.tracking_numbering
                  }
                })
              })
                .then(res => {
                  this.$message.success('保存成功!')
                  setTimeout(_ => {
                    this.$router.push({ name: 'order_list' })
                  }, 1000)
                  resolve()
                })
                .finally(_ => {
                  state.submitButtonLoading = false
                })
            })
            .catch(err => {
              state.submitButtonLoading = false
              reject(err)
            })
        })
      },
      removeTrackingNumbering (index) {
        const { form } = this

        const information = form.getFieldValue('courier_information')
        delete information[index] // 这里不能用 Vue.delete 会导致 index 对不准, 在提交的时候 再做 null 过滤

        const numbering = form.getFieldValue('tracking_numbering')
        Vue.delete(numbering, numbering.indexOf(index))

        form.setFieldsValue({
          tracking_numbering: numbering
        })
      },
      addTrackingNumbering () {
        const { form } = this
        const numbering = form.getFieldValue('tracking_numbering')

        form.setFieldsValue({
          tracking_numbering: numbering.concat(trackingNumberingSort++)
        })
      }
    }
  }
</script>

<style scoped>

</style>
